/* eslint-disable react-hooks/rules-of-hooks */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react';
import { connect } from 'dva';
import { ModalC, PrimaryGhostC, FundApplicationIndustryC, SelectC, TableC, QuickQueryC } from '@/src/comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import config from '../../../../comps/business/tradingMarket/config';
import myStyle from '../index.less';
import { findValueByCode, formSelectData } from '@/src/utils/utils';
import uuid from 'es6-uuid';
import { message } from 'antd';

const infoModal = ({
  visible,
  changeVisible,
  loading,
  dispatch,
  form,
  globalM: {
    dataDictionary: { SMART_BETA_RATING = [], GJTJJHYFLI = [], ISSUER_BY_SIZE = [] },
  },
}) => {
  const [isModalOpen, setIsModalOpen] = useState(visible); // 弹窗与否
  const [dataSource, setDataSource] = useState([]); // 列表data
  const [clickRow, setClickRow] = useState(undefined); // 正在点击的行数据
  const [oldRow, setOldRow] = useState(undefined); // 存放当前编辑的行旧值
  const [searchFlag, setSearchFlag] = useState('all'); // 根据全部、行业、规模和评级比较的标志位
  const [pageInfo, setPageInfo] = useState({
    numInPage: 20,
    currentPage: 1,
    total: 0,
  });
  const columns = [
    { title: '证券代码', key: 'tradingcode' },
    { title: '证券名称', key: 'secuabbr' },
    {
      title: '交易市场',
      key: 'exchangecode',
      render: (text, record) => {
        let temp = '--';
        config.map((item) => {
          if (item.value === text) {
            temp = item.title;
          }
        });
        return temp;
      },
    },
    {
      title: '系统',
      children: [
        {
          title: '行业',
          key: 'systemIndustry',
          width: 220,
          render: (text, record) => {
            if (record.isEdit) {
              return (
                <FundApplicationIndustryC
                  form={form}
                  dataIndex='systemIndustry'
                  title=''
                  initialValue={text}
                  OnlySupportFirstLevel={true}
                  parentCanClick={true}
                  positionBody={true}
                  rules={[{ required: true, message: '请选择' }]}
                />
              );
            }
            return findValueByCode(text, GJTJJHYFLI);
          },
        },
        {
          title: '规模',
          key: 'systemScale',
          width: 150,
          render: (text, record) => {
            if (record.isEdit) {
              return (
                <SelectC
                  form={form}
                  dataIndex='systemScale'
                  title=''
                  initialValue={text}
                  positionBody={true}
                  dataSource={formSelectData(ISSUER_BY_SIZE)}
                  rules={[{ required: true, message: '请选择' }]}
                />
              );
            }
            return findValueByCode(text, ISSUER_BY_SIZE);
          },
        },
        {
          title: '评级',
          key: 'systemRating',
          render: (text, record) => {
            if (record.isEdit) {
              return (
                <SelectC
                  form={form}
                  dataIndex='systemRating'
                  title=''
                  initialValue={text}
                  positionBody={true}
                  dataSource={formSelectData(SMART_BETA_RATING)}
                  rules={[{ required: true, message: '请选择' }]}
                />
              );
            }
            if (text == 'NOT_RATED') {
              text = '无评级';
            }
            return text || '--';
          },
        },
      ],
    },
    {
      title: '资讯',
      children: [
        {
          title: '行业',
          key: 'infoIndustry',
          width: 220,
          render: (text, record) => {
            return findValueByCode(text, GJTJJHYFLI);
          },
        },
        {
          title: '规模',
          key: 'infoScale',
          render: (text, record) => {
            return findValueByCode(text, ISSUER_BY_SIZE);
          },
        },
        {
          title: '评级',
          key: 'infoRating',
          render: (text, record) => {
            if (text == 'NOT_RATED') {
              text = '无评级';
            }
            return text || '--';
          },
        },
      ],
    },

    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      type: 'operate',
      fixed: 'right',
      width: 120,
      operates: [
        {
          title: '保存',
          onClick: (record) => {
            saveItem(record);
          },
          rules: {
            // 点击保存或取消时隐藏保存和取消按钮，展示编辑
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
          },
        },
        {
          title: '取消',
          onClick: (record, index) => {
            cancelItem(record);
          },
          rules: {
            // 点击保存或取消时隐藏保存和取消按钮，展示编辑
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['='] }] },
          },
        },
        {
          title: '编辑',
          onClick: (record, index) => {
            editItem(record);
          },
          rules: {
            hide: { items: [{ key: 'isEdit', value: [undefined], relation: ['!='] }] },
          },
        },
      ],
    },
  ];

  // useEffect(() => {
  //     getInfoData();//获取列表
  // }, []); // 仅首次加载的时候进入
  const handleOk = () => {
    handleCancel();
  };
  const handleCancel = () => {
    setIsModalOpen(false);
    // 通知父组件关闭弹窗
    changeVisible(false);
  };
  const onRefrish = () => {
    // 刷新的时候 从第一页查询
    const page = pageInfo.currentPage;
    pageInfo.currentPage = 1;
    setPageInfo({ ...pageInfo });
    if (page === 1) getInfoData(); // 本身就在第一页 不会触发 所以单独获取列表
  };
  // 保存数据
  const saveItem = (row) => {
    // 这里取不到state里的数据，所以只能保存了当前点击行的数据
    const { validateFields } = form;
    validateFields((err, values) => {
      if (err) return;
      // 因接口请求慢 页面先恢复
      const dataArr = dataSource.map((item) => {
        if (item.id === row.id) {
          // eslint-disable-next-line no-param-reassign
          item = {
            ...item,
            ...values,
          };
          item.isEdit = undefined;
          item.key = uuid(16);
        }
        return item;
      });
      setDataSource([...dataArr]);
      dispatch({
        type: 'manbondInfoM/saveInfoData',
        payload: {
          ...values,
          id: row.id,
        },
        callback: () => {
          setClickRow(undefined);
          setOldRow(undefined);
        },
      });
    });
  };
  // 点击取消
  const cancelItem = (row) => {
    /// 这里取不到state里的数据，所以只能保存了当前点击行的数据
    const temp = _.cloneDeep(row);
    temp.isEdit = undefined;
    setClickRow({ ...temp });
    setOldRow(undefined); // 删除缓存的编辑行
  };
  // 点击编辑
  const editItem = (row) => {
    // 这里取不到state里的数据，所以只能保存了当前点击行的数据
    const temp = _.cloneDeep(row);
    temp.isEdit = true;
    setClickRow({ ...temp });
  };

  useEffect(() => {
    console.log('进入编辑,取消', clickRow, oldRow);
    if (dataSource?.length && clickRow) {
      if (oldRow && clickRow?.id != oldRow.id) {
        // 用当点击行的数据id 与 正在编辑的行的缓存对比
        message.warning('有正在编辑中的数据，请保存后再进行操作！');
        return;
      }
      dataSource.map((item) => {
        if (clickRow.id === item.id) {
          item.isEdit = clickRow.isEdit;
          item.key = uuid(16); // 为了编辑的时候页面能够渲染
          return { ...item };
        }
      });
      setDataSource([...dataSource]);
      if (clickRow.isEdit) setOldRow(clickRow); // 缓存正在编辑的行
    }
  }, [clickRow]); //
  // 获取同发行人数据
  const getInfoData = () => {
    setOldRow(undefined); // 删除缓存的数据
    setClickRow(undefined);
    // console.log(searchFlag, pageInfo)
    dispatch({
      type: 'manbondInfoM/getInfoData',
      payload: {
        searchFlag,
        numInPage: pageInfo?.numInPage,
        currentPage: pageInfo?.currentPage,
      },
      callback: (data) => {
        if (data) {
          setDataSource(data.dataSource ? [...data.dataSource] : []);
          pageInfo.total = data.pageInfo?.total;
          setPageInfo({ ...pageInfo });
        } else {
          setDataSource([]);
        }
      },
    });
  };
  // 根据查询条件变化 进行请求列表数据
  useEffect(() => {
    console.log('状态变化了，请求');
    getInfoData();
    // eslint-disable-next-line eslint-comments/no-duplicate-disable
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [searchFlag, pageInfo.numInPage, pageInfo.currentPage]);
  // 表格分页切换
  const handleTableChange = (pagination, filters) => {
    const { current, pageSize } = pagination;
    setPageInfo({
      currentPage: current,
      numInPage: pageSize,
    });
  };

  return (
    <div>
      <ModalC title={'资讯对比校验'} visible={isModalOpen} maskClosable={false} onOk={handleOk} onCancel={handleCancel} width={1600} footer={null}>
        <div className={myStyle.modalCls}>
          <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <QuickQueryC
              dataSource={[
                { value: 'all', title: '全部' },
                { value: 'industry', title: '仅行业' },
                { value: 'scale', title: '仅规模' },
                { value: 'rating', title: '仅评级' },
              ]}
              initialValue='all'
              onChange={(e) => {
                // 切换的时候 从第一页查询
                pageInfo.currentPage = 1;
                setPageInfo({ ...pageInfo });
                setSearchFlag(e);
              }}
            />
            <PrimaryGhostC title='刷新' onClick={onRefrish} style={{ marginBottom: '15px' }} />
          </div>
          <TableC
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            scroll={{ y: 500 }}
            // hidePage={true}
            rowKey='key'
            current={pageInfo?.currentPage}
            pageSize={pageInfo?.numInPage}
            total={pageInfo?.total}
            onChange={handleTableChange}
          />
        </div>
      </ModalC>
    </div>
  );
};
const mapState = ({ manbondInfoM, globalM, loading }) => ({ manbondInfoM, globalM, loading: loading.effects['manbondInfoM/getInfoData'] });
export default connect(mapState)(Form.create()(infoModal));
